package com.gavinandre.socket;


import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
	public static void main(String[] args) {
		PrintWriter pw = null;
		Scanner scan = null;
		ServerSocket ss = null;
		Socket socket = null;
		try {
			//创建服务端
			ss = new ServerSocket(10086);
			System.out.println("启动服务！");

			//等待客户端连接，获取客户端对象
			socket = ss.accept();

			//开启一个子线程，用于自动接收客户端发来的消息
			ServerTarget st = new ServerTarget(socket);
			Thread t = new Thread(st);
			t.start();


			//获取服务端的键盘监听
			scan = new Scanner(System.in);

			//获取用于发送消息的打印流
			pw = new PrintWriter(socket.getOutputStream(), true);//自动刷新

			while(true){
				System.out.println("请输入消息内容：");
				String serverMsg = scan.nextLine();//获取服务端键盘输入的内容
				pw.println(serverMsg);//发送消息

			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//关闭资源
			try {
				pw.close();
				scan.close();
				socket.close();
				ss.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
